package com.mzy.redis.service.impl;

import com.mzy.redis.service.PhoneService;
import com.mzy.redis.utils.PhoneUtil;
import javafx.util.Duration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class PhoneServiceImpl implements PhoneService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String getCode(String phone) {
        // 1. 生成验证码
        String code = PhoneUtil.getCode(6);
        // 2. 将验证码存入 redis 并设置2分钟过期
        redisTemplate.opsForValue().set(phone + ":code", code, 120, TimeUnit.SECONDS);
        return code;
    }

    @Override
    public Boolean register(String phone, String code) {
        if (code == null) return false;
        if (code.equals(redisTemplate.opsForValue().get(phone + ":code"))) {
            redisTemplate.expire(phone+":code", -1, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }


}
